<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>并发请求</h1>
    <script>
      const urls = [];

      for (let i = 0; i < 20; i++) {
        urls.push(`https://jsonplaceholder.typicode.com/todos/${i + 1}`);
      }

      /**
       * 并发请求
       * @param {*} urls 地址数组
       * @param {*} maxNum 最大并发数
       */
      function convertData(urls, maxNum) {
        if (urls.length === 0) {
          return Promise.resolve([]);
        }

        return new Promise((reslove) => {
          const result = [];
          let nextIndex = 0;
          let resultIndex = 0;
          async function _request() {
            if (nextIndex >= urls.length) {
              return;
            }
            let i = nextIndex;
            const url = urls[nextIndex++];
            const data = await fetch(url);
            result[i] = data;
            resultIndex++;
            if (resultIndex === urls.length) {
              reslove(result);
            }
            _request();
          }

          for (let i = 0; i < maxNum; i++) {
            _request();
          }
        });
      }
      convertData(urls, 3).then((res) => {
        console.log(res);
      });
    </script>
  </body>
</html>
